<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="80px"
    >
      <el-form-item label="学生邮箱" prop="studentEmail">
        <el-input
          v-model="dataForm.studentEmail"
          placeholder="学生邮箱"
        ></el-input>
      </el-form-item>
      <el-form-item label="学生姓名" prop="studentName">
        <el-input
          v-model="dataForm.studentName"
          placeholder="学生姓名"
        ></el-input>
      </el-form-item>
      <el-form-item label="用户名" prop="studentUsername">
        <el-input
          v-model="dataForm.studentUsername"
          placeholder="用户名"
        ></el-input>
      </el-form-item>


      <el-form-item label="头像" prop="studentAvatar">
        <div class="avatar-container">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8888/api/minio/upload"
            :show-file-list="false"
            :on-preview="handlePictureCardPreview"
            :on-success="handleUploadSuccess"
            :before-upload="beforeAvatarUpload"
           >
            <img style="width: 150px;height: 150px"  v-if="dataForm.studentAvatar" :src="dataForm.studentAvatar" class="avatar" alt="">
            <el-button v-else size="small" type="primary">点击上传</el-button>
          </el-upload>
        </div>
      </el-form-item>



      <el-form-item label="出生日期" prop="studentAge">
        <el-date-picker
          v-model="dataForm.studentAge"
          type="date"
          placeholder="选择日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="性别">
        <el-radio-group v-model="dataForm.studentGender">
          <el-radio label="男"></el-radio>
          <el-radio label="女"></el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="个性签名" prop="studentIntroduction">
        <el-input
          v-model="dataForm.studentIntroduction"
          placeholder="个性签名"
        ></el-input>
      </el-form-item>


      <el-form-item label="学历等级" prop="levelName">
        <el-select v-model="dataForm.levelName" placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.levelName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>


    <span slot="footer" class="dialog-footer">
      <el-button @click="close">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data () {
    return {
      visible: false,
      dataForm: {
        id: 0,
        studentEmail: '',
        studentName: '',
        studentUsername: '',
        studentPassword: '',
        studentAvatar: '',
        studentAge: '',
        studentIntroduction: '',
        levelName: '',
        createTime: '',
        updateTime: '',
        isDelete: '',
        studentGender: ''
      },
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: [
        {
          name: '',
          url: ''
        }
      ],
      imageUrl: '',
      flag: true,
      options: [],
      dataRule: {
        studentEmail: [
          { required: true, message: '学生邮箱不能为空', trigger: 'blur' }
        ],
        studentName: [
          { required: true, message: '学生姓名不能为空', trigger: 'blur' }
        ],
        studentUsername: [
          { required: true, message: '姓名不能为空', trigger: 'blur' }
        ],
        studentPassword: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ],
        studentAvatar: [
          { required: true, message: '头像不能为空', trigger: 'blur' }
        ],
        studentAge: [
          { required: true, message: '学生年龄不能为空', trigger: 'blur' }
        ],
        studentIntroduction: [
          { required: true, message: '个性签名不能为空', trigger: 'blur' }
        ],
        levelName: [
          { required: true, message: '学历等级不能为空', trigger: 'blur' }
        ],
        createTime: [
          { required: false, message: '创建时间不能为空', trigger: 'blur' }
        ],
        updateTime: [
          { required: false, message: '修改时间不能为空', trigger: 'blur' }
        ]
      }
    };
  },
  created () {
    this.updateFlag();
  },
  methods: {
    init (id) {
      this.getStudentLevel();
      this.dataForm.id = id || 0;
      this.visible = true;
      this.updateFlag();
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields();
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(
              `/student/student/findStudentDetailById/${this.dataForm.id}`
            ),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 0) {
              console.log(data.detail);
              console.log(typeof data.detail.levelName, '111');

              this.dataForm.studentEmail = data.detail.studentEmail;
              this.dataForm.studentName = data.detail.studentName;
              this.dataForm.studentUsername = data.detail.studentUsername;
              this.dataForm.studentPassword = data.detail.studentPassword;
              this.dataForm.studentAvatar = data.detail.studentAvatar;
              this.dataForm.studentAge = data.detail.studentAge;
              this.dataForm.studentIntroduction =
                data.detail.studentIntroduction;
              this.dataForm.levelName = data.detail.levelName;
              this.dataForm.createTime = data.detail.createTime;
              this.dataForm.updateTime = data.detail.updateTime;
              this.dataForm.isDelete = data.detail.isDelete;
              this.dataForm.studentGender = data.detail.studentGender;
            }
          });
        }
      });
    },
    // 表单提交
    dataFormSubmit () {
      this.$refs['dataForm'].validate((valid) => {
        // eslint-disable-next-line no-undef
        this.setLevelId();
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `/student/student/${!this.dataForm.id ? 'save' : 'update'}`
            ),
            method: 'post',
            data: this.$http.adornData({
              id: this.dataForm.id || undefined,
              studentEmail: this.dataForm.studentEmail,
              studentName: this.dataForm.studentName,
              studentUsername: this.dataForm.studentUsername,
              studentPassword: this.dataForm.studentPassword,
              studentAvatar: this.dataForm.studentAvatar,
              studentAge: new Date(this.dataForm.studentAge),
              studentIntroduction: this.dataForm.studentIntroduction,
              levelName: this.dataForm.levelName,
              createTime: this.dataForm.createTime,
              updateTime: this.dataForm.updateTime,
              isDelete: this.dataForm.isDelete,
              studentGender: this.dataForm.studentGender
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              console.log(this.dataForm.levelName, '6666');
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  console.log(this.dataForm.levelName, 'sadas');
                  this.$emit('refreshDataList');

                  this.fileList = [];
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },
    // 获取学生学历等级数据
    getStudentLevel () {
      this.$http({
        url: this.$http.adornUrl(
          '/student/studentlevel/findStudentLevelNameList'
        ),
        method: 'get'
      }).then(({ data }) => {
        if (data && data.code === 0) {
          console.log(data.levelNameList);
          this.options = data.levelNameList;
        } else {
          this.options = [];
        }
      });
    },

    // 打开编辑框的时候为等级设置对应的id
    setLevelId () {
      if (typeof this.dataForm.levelName === 'string') {
        for (var i = 0; i < this.options.length; i++) {
          if (
            this.dataForm.id &&
            this.dataForm.levelName === this.options[i].levelName
          ) {
            this.dataForm.levelName = this.options[i].id;
          }
          console.log(this.dataForm.levelName, 'sadas');
        }
      }
    },

    handlePreview (file) {
      console.log(file);
    },

    handleRemove (file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview (file) {
      console.log(file);
      this.dataForm.studentAvatar = file.url;
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleUploadSuccess (res, file) {
      console.log(res, 'res')
      console.log(file, 'file')
      this.dataForm.studentAvatar = res.msg

      // this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload (file) {
      console.log(file.type, 'file')
      const isJPG = file.type === 'image/jpeg';
      const isPng = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPng) {
        this.$message.error('上传头像图片只能是 JPG或PNG格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return (isJPG || isPng) && isLt2M;
    },
    updateFlag () {
      this.flag = this.dataForm.studentAvatar !== '';
      console.log(this.flag);
    },
    close () {
      this.visible = false;
      this.handleRemove(this.fileList);
    }
  }
};
</script>
<style>
.avatar-container {
  display: flex;
}

</style>
